package z.explorer.ui.component.navigator;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import z.explorer.ui.common.ZProgressDialog;

public class ZTree extends JTree {
	static ImageIcon leaf = null;
	static ImageIcon close = null;
	static ImageIcon open = null;

	static {
		initResource();
	}

	public ZTree(ZTreeNode root) {
		super();

		putClientProperty("JTree.lineStyle", "Angled");
		DefaultTreeModel model = new DefaultTreeModel(root);
		setModel(model);
		DefaultTreeCellRenderer dtcr = (DefaultTreeCellRenderer) getCellRenderer();
		dtcr.setLeafIcon(leaf);
		dtcr.setOpenIcon(open);
		dtcr.setClosedIcon(close);
		addMouseListener(new MouseOnTree());
	}

	public static void initResource() {
		URL leaf_url = ZTree.class.getResource("/z/explorer/resource/leaf.gif");
		URL close_url = ZTree.class
				.getResource("/z/explorer/resource/close.gif");
		URL open_url = ZTree.class.getResource("/z/explorer/resource/open.gif");
		leaf = new ImageIcon(leaf_url);
		close = new ImageIcon(close_url);
		open = new ImageIcon(open_url);

	}

	class MouseOnTree extends MouseAdapter {

		@Override
		public void mouseClicked(MouseEvent evt) {
			// TODO Auto-generated method stub
			if (evt.getClickCount() == 2) {
				TreePath path = ZTree.this.getPathForLocation(evt.getX(), evt
						.getY());
				if(path!=null){
					ZTreeNode node = (ZTreeNode)path.getLastPathComponent();
					if(node.isLeaf()){
						ZProgressDialog zpd=new ZProgressDialog(null,node.getHandler());
						zpd.run();
					}
				}
			}
		}

	}

	/* for test */
	public static void main(String args[]) {
		URL url = JTree.class.getResource("/z/explorer/resource/leaf.gif");
		System.out.println(url);
	}
}
